/*
*
* wd14931 mvc
*
* */
var Url       = require('url');
var ex        = require('./../handleEx');
var filesTree = require('./../tools/readControllerFiles');

module.exports = function(req, res, next){

  var pathname = Url.parse(req.url).pathname;
  var paths = pathname.split('/');
  var controller = paths[1]? paths[1].replace(/^(.)/g, function($0){return $0.toUpperCase();}) : 'index';
  var action = paths[2] || 'index';
  var args = paths.slice(3);
  var module;

  if(filesTree.files.indexOf(controller + 'Controller.js') === -1){
    controller = 'index';
    action     = 'index';
  }

  try{
    // require的缓存机制使得首次是阻塞的；
    module = require('./../controllers/' + controller + 'Controller');

  }catch(e){

    ex.handle500(e, req, res, next);
    return;
  }

  var method = module[action];

  if(method){
    method.apply(null, [req, res].concat(args));
  }else{
    ex.handle500(new Error('Not Found ' + method), req, res, next);
  }
}
